package org.xxpay.pay.channel.huixin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Component;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.util.DateUtils;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.channel.haitian.HaitianConfig;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class HuixinPaymentService extends BasePayment {

    private final static String logPrefix = "【汇鑫】";

    // 下单
    private final static String ORDER_CREATE_STR = "/ApiPay.aspx";
    // 订单查询
    private final static String ORDER_QUERY_STR = "/api/query";
    @Override
    public String getChannelName() {
        return HuixinConfig.CHANNEL_NAME;
    }

    /**
     * 支付下单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject pay(PayOrder payOrder){
        String channelId = payOrder.getChannelId();
        JSONObject retObj;
        switch (channelId) {
            case HuixinConfig.CHANNEL_NAME_QUICK_WAP:
                retObj = doOrderReq(payOrder);
                break;
            default:
                retObj = buildRetObj(PayConstant.RETURN_VALUE_FAIL, "不支持的渠道[channelId="+channelId+"]");
                break;
        }
        return retObj;
    }

    //下单实现
    private JSONObject doOrderReq(PayOrder payOrder){
        HuixinConfig config = new HuixinConfig(getPayParam(payOrder));
        // 请求参数
        Map<String,Object> params = setPublicParams(payOrder,config);

        _log.info("{}请求数据:{}", getChannelName(), JSON.toJSONString(params));

        // 将订单改为支付中
        rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);

        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);

        JSONObject  result = requestTemplate.postForObject(getReqUrl(config.getRequestUrl(),ORDER_CREATE_STR), params, JSONObject.class);
        _log.info("{}响应参数：{}", logPrefix, result);
        JSONObject retObj = new JSONObject();
        if(result.getString("retCode").equals("RC0002")){
            // 支付链接地址
            String codeUrl = result.getString("qrCodeVal");
            return buildPayResultOfForm(retObj, payOrder,getHtml(codeUrl));
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, result.getString("retRemark"));
        return retObj;
    }

    //设置请求参数
    private  Map<String,Object> setPublicParams(PayOrder payOrder, HuixinConfig config){
        Map<String,Object> params = new HashMap<>();
        params.put("version", HuixinConfig.VIL_VERSION_VAlUE);
        params.put("charset", HuixinConfig.VIL_CHARSET_VAlUE);
        params.put("merId", config.getMchId());
        params.put("orderTime", DateUtils.YYYYMMDDHHMMSS.format(new Date()));
        params.put("transCode", "T0202");
        params.put("signType", HuixinConfig.VIL_SIGN_TYPE_VAlUE);
        params.put("transactionId", payOrder.getPayOrderId());
        params.put("orderAmount", AmountUtil.convertCent2Dollar(String.valueOf(payOrder.getAmount())));
        params.put("payType", "3002");
        params.put("bgUrl",payConfig.getNotifyUrl(getChannelName()));
        params.put("pageUrl",payOrder.getReturnUrl());
        params.put("signData", getSign(params, config.getPrivateKey()));
        params.put("mch_create_ip", payOrder.getClientIp());
        return params;
    }
    //获取签名
    private String getSign(Map<String,Object> params,String key){
        String signTxt = SignUtils.parameterText(params);
        _log.info("{}支付签名字符串：{}", logPrefix, signTxt);
        String sign = SignUtils.MD5.createSign(signTxt, "&key="+key, SignUtils.CHARSET_UTF8);
        return sign.toUpperCase();
    }

    //获取请求html
    private String getHtml(String payUrl){
        StringBuffer buffer = new StringBuffer();
        buffer.append("<script type=\"text/javascript\">");
        buffer.append("window.location.href=\""+payUrl+"\"");
        buffer.append("</script>");
        return buffer.toString();
    }
}
